package com.foodorder.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class DirectPasswordFix {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Bean
    public CommandLineRunner fixAdminPassword() {
        return args -> {
            String password = "123456";
            String encodedPassword = passwordEncoder.encode(password);
            System.out.println("直接修复管理员密码中...");
            System.out.println("密码: " + password);
            System.out.println("加密后: " + encodedPassword);
            
            // 1. 检查管理员是否存在
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM admins WHERE username = ?", 
                Integer.class, 
                "admin"
            );
            
            if (count != null && count > 0) {
                // 更新密码
                int updated = jdbcTemplate.update(
                    "UPDATE admins SET password = ? WHERE username = ?",
                    encodedPassword, "admin"
                );
                System.out.println("管理员密码更新成功，影响 " + updated + " 条记录");
            } else {
                // 插入新管理员
                int inserted = jdbcTemplate.update(
                    "INSERT INTO admins (username, password, name, phone, email, avatar, role, status, permissions, created_at, updated_at) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
                    "admin", encodedPassword, "系统管理员", "13800138000", "admin@foodorder.com", 
                    "/images/avatars/admin.jpg", "SUPER_ADMIN", "ACTIVE", "ALL"
                );
                System.out.println("新管理员账号创建成功，影响 " + inserted + " 条记录");
            }
        };
    }
} 